package com.cms.intelligent_control.common.http.converter


import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter
import retrofit2.Retrofit
import java.io.IOException
import java.lang.reflect.Type

class JsonConverterFactory private constructor() : Converter.Factory() {

    companion object {
        fun create(): JsonConverterFactory {
            return JsonConverterFactory()
        }
    }

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *>? {
        return if (type === JSONObject::class.java) {
            JsonResponseBodyConverter.INSTANCE
        } else {
            null
        }
    }
}

internal class JsonResponseBodyConverter : Converter<ResponseBody, JSONObject> {

    companion object {
        val INSTANCE = JsonResponseBodyConverter()
    }

    @Throws(IOException::class)
    override fun convert(value: ResponseBody): JSONObject? {
        return JSONObject(value.string())
    }
}
